<template>
  <div class="relationship-graph" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  data: {
    type: Object, // { nodes: [], edges: [] }
    default: () => ({ nodes: [], edges: [] })
  }
});

const chartRef = ref(null);
let chartInstance = null;

const initChart = () => {
  if (!chartRef.value) return;
  
  chartInstance = echarts.init(chartRef.value);
  
  const option = {
    title: {
      text: '关系网络图谱',
      top: 'bottom',
      left: 'right'
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
          if (params.dataType === 'node') {
              return `<strong>${params.data.name}</strong><br/>Type: ${params.data.category || 'Unknown'}`;
          } else {
              return `<strong>${params.data.relation_type || 'Relation'}</strong><br/>Weight: ${params.data.weight}`;
          }
      }
    },
    legend: [{
      data: ['person', 'company', 'account'].map(a => a)
    }],
    series: [
      {
        type: 'graph',
        layout: 'force',
        data: [],
        links: [],
        categories: [
            { name: 'person', itemStyle: { color: '#409EFF' } },
            { name: 'company', itemStyle: { color: '#E6A23C' } },
            { name: 'account', itemStyle: { color: '#67C23A' } }
        ],
        roam: true,
        label: {
          show: true,
          position: 'right',
          formatter: '{b}'
        },
        lineStyle: {
          color: 'source',
          curveness: 0.3
        },
        force: {
          repulsion: 300,
          edgeLength: 100
        }
      }
    ]
  };
  
  chartInstance.setOption(option);
  window.addEventListener('resize', resizeHandler);
};

const updateChart = () => {
    if (!chartInstance) return;
    
    // Transform nodes/edges if necessary
    const nodes = props.data.nodes.map(n => ({
        id: n.id,
        name: n.name || n.id,
        category: getCategory(n.type),
        symbolSize: n.risk_score ? 20 + n.risk_score : 30,
        ...n
    }));
    
    const links = props.data.edges.map(e => ({
        source: e.source,
        target: e.target,
        value: e.weight,
        ...e
    }));

    chartInstance.setOption({
        series: [{
            data: nodes,
            links: links
        }]
    });
};

const getCategory = (type) => {
    // Map internal types to category names
    if (type === 'person') return 0; // index in categories
    if (type === 'company') return 1;
    return 2;
};

const resizeHandler = () => {
    chartInstance?.resize();
};

onMounted(() => {
  initChart();
  if (props.data && props.data.nodes.length) {
      updateChart();
  }
});

watch(() => props.data, () => {
    updateChart();
}, { deep: true });

onUnmounted(() => {
    window.removeEventListener('resize', resizeHandler);
    chartInstance?.dispose();
});
</script>

<style scoped>
.relationship-graph {
  width: 100%;
  height: 600px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>
